from flask import Blueprint, request, jsonify
from src.models.database import db, PredictionTask, PredictionResult, HistoricalData
from src.models.metaso_data import MetasoQueryData
from src.services.prediction_service import PredictionService
from src.services.llm_service import LLMService
import json
import uuid
from datetime import datetime

prediction_bp = Blueprint('prediction', __name__)
prediction_service = PredictionService()

@prediction_bp.route('/tasks', methods=['POST'])
def create_prediction_task():
    """创建预测任务"""
    try:
        data = request.get_json()
        
        # 验证必要参数
        task_type = data.get('task_type', 'multi_product')
        
        if task_type == 'group_prediction':
            # 集团预测只需要任务名称和预测年份
            required_fields = ['task_name', 'prediction_years']
        else:
            # 其他类型需要公司ID
            required_fields = ['task_name', 'company_ids', 'prediction_years']
        
        for field in required_fields:
            if field not in data:
                return jsonify({'code': 400, 'message': f'缺少必要参数: {field}'}), 400
        
        # 创建任务
        task_id = str(uuid.uuid4())
        
        # 处理集团预测的特殊参数
        if task_type == 'group_prediction':
            # 集团预测将战略增速参数存储在description字段中
            task_params = {
                'strategic_growth_rates': data.get('strategic_growth_rates', {})
            }
            description = json.dumps(task_params)
            
            task = PredictionTask(
                task_id=task_id,
                task_name=data['task_name'],
                task_type=task_type,
                company_ids=json.dumps([]),  # 集团预测不需要公司ID
                product_ids=json.dumps([]),
                prediction_years=json.dumps(data['prediction_years']) if isinstance(data['prediction_years'], list) else json.dumps([data['prediction_years']]),
                description=description,
                status='pending',
                created_by=data.get('created_by', 'system')
            )
        else:
            # 其他类型的任务
            task = PredictionTask(
                task_id=task_id,
                task_name=data['task_name'],
                task_type=task_type,
                company_ids=json.dumps(data['company_ids']),
                product_ids=json.dumps(data.get('product_ids', [])),
                prediction_years=json.dumps(data['prediction_years']) if isinstance(data['prediction_years'], list) else json.dumps([data['prediction_years']]),
                description=data.get('description', ''),
                status='pending',
                created_by=data.get('created_by', 'system')
            )
        
        db.session.add(task)
        db.session.commit()
        
        # 同步执行预测任务（避免异步问题）
        try:
            prediction_service._execute_prediction_task(task_id)
        except Exception as e:
            print(f"❌ 任务执行失败: {str(e)}")
            # 不抛出异常，让任务创建成功，但状态会是failed
        
        return jsonify({
            'code': 200,
            'message': '预测任务创建成功',
            'data': {
                'task_id': task_id,
                'status': 'pending'
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'创建任务失败: {str(e)}'}), 500

@prediction_bp.route('/tasks/<task_id>/status', methods=['GET'])
def get_task_status(task_id):
    """查询任务状态"""
    try:
        task = PredictionTask.query.filter_by(task_id=task_id).first()
        
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': task.to_dict()
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@prediction_bp.route('/tasks/<task_id>/results', methods=['GET'])
def get_task_results(task_id):
    """获取预测结果"""
    try:
        task = PredictionTask.query.filter_by(task_id=task_id).first()
        
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        if task.status != 'completed':
            return jsonify({'code': 400, 'message': '任务尚未完成'}), 400
        
        # 获取预测结果
        results = PredictionResult.query.filter_by(task_id=task_id).all()
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'task': task.to_dict(),
                'results': [result.to_dict() for result in results]
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@prediction_bp.route('/tasks', methods=['GET'])
def get_prediction_tasks():
    """获取预测任务列表"""
    try:
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 20, type=int)
        status = request.args.get('status')
        
        query = PredictionTask.query.order_by(PredictionTask.created_at.desc())
        
        if status:
            query = query.filter(PredictionTask.status == status)
        
        pagination = query.paginate(
            page=page,
            per_page=page_size,
            error_out=False
        )
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'items': [task.to_dict() for task in pagination.items],
                'total': pagination.total,
                'page': page,
                'page_size': page_size,
                'pages': pagination.pages
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@prediction_bp.route('/tasks/<task_id>', methods=['DELETE'])
def cancel_prediction_task(task_id):
    """取消预测任务"""
    try:
        task = PredictionTask.query.filter_by(task_id=task_id).first()
        
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        if task.status in ['completed', 'failed']:
            return jsonify({'code': 400, 'message': '任务已完成，无法取消'}), 400
        
        # 更新任务状态
        task.status = 'cancelled'
        task.completed_at = datetime.utcnow()
        db.session.commit()
        
        # 停止后台任务
        prediction_service.cancel_task(task_id)
        
        return jsonify({
            'code': 200,
            'message': '任务已取消'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'取消任务失败: {str(e)}'}), 500

@prediction_bp.route('/results/summary', methods=['GET'])
def get_prediction_summary():
    """获取预测结果汇总"""
    try:
        task_id = request.args.get('task_id')
        
        if not task_id:
            return jsonify({'code': 400, 'message': '缺少任务ID'}), 400
        
        summary = prediction_service.get_prediction_summary(task_id)
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': summary
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@prediction_bp.route('/models/accuracy', methods=['GET'])
def get_model_accuracy():
    """获取模型准确率统计"""
    try:
        accuracy_stats = prediction_service.get_model_accuracy_stats()
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': accuracy_stats
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@prediction_bp.route('/report/<task_id>', methods=['GET'])
def get_report_data(task_id):
    """获取报表数据"""
    try:
        print(f"查找报表数据，任务ID: {task_id}")
        
        # 获取任务信息 - 支持数字ID和UUID
        task = None
        if task_id.isdigit():
            # 如果是数字，按数据库ID查询
            task = PredictionTask.query.filter_by(id=int(task_id)).first()
            print(f"按数字ID查询: {task_id}")
        else:
            # 如果是字符串，按task_id查询
            task = PredictionTask.query.filter_by(task_id=task_id).first()
            print(f"按UUID查询: {task_id}")
        
        if not task:
            print(f"任务不存在: {task_id}")
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        print(f"找到任务: {task.task_name}, UUID: {task.task_id}")
        
        # 检查AI分析文件是否存在
        llm_service = LLMService()
        ai_analysis_exists = llm_service.check_ai_analysis_file_exists(task.task_id)
        ai_analysis_content = None
        
        if ai_analysis_exists:
            ai_analysis_content = llm_service.get_ai_analysis_from_file(task.task_id)
            print(f"从文件读取AI分析结果，长度: {len(ai_analysis_content) if ai_analysis_content else 0}")
        else:
            print(f"AI分析文件不存在: {task.task_id}")
        
        # 获取Metaso数据（行业增长率和市场阶段CAGR）
        metaso_data = MetasoQueryData.query.all()
        metaso_overview = []
        
        # 按板块分组Metaso数据
        sectors_map = {
            '人药制剂': '人药制剂板块',
            '人药原料': '人药原料药板块', 
            '植保': '植保板块',
            '动保': '动保板块'
        }
        
        for sector_key, sector_name in sectors_map.items():
            # 查找该板块的最新有效数据（industry_cagr和market_stage_cagr都不为None）
            sector_metaso = MetasoQueryData.query.filter(
                MetasoQueryData.sector_name.like(f'%{sector_key}%'),
                MetasoQueryData.industry_cagr.isnot(None),
                MetasoQueryData.market_stage_cagr.isnot(None)
            ).order_by(MetasoQueryData.created_at.desc()).first()
            
            if sector_metaso:
                metaso_overview.append({
                    'sector_name': sector_name,
                    'industry_cagr': sector_metaso.industry_cagr,
                    'market_stage_cagr': sector_metaso.market_stage_cagr,
                    'data_sources': 1  # 简化显示
                })
                print(f"找到{sector_name}最新有效数据: industry_cagr={sector_metaso.industry_cagr}, market_stage_cagr={sector_metaso.market_stage_cagr}")
            else:
                print(f"未找到{sector_name}的有效Metaso数据")
        
        # 获取历史数据
        historical_data = []
        historical_records = HistoricalData.query.all()
        
        # 按单位和指标分组历史数据
        data_by_unit = {}
        for record in historical_records:
            unit = record.business_unit
            if unit not in data_by_unit:
                data_by_unit[unit] = {}
            
            # 根据指标名称和年份存储数据
            metric = record.metric_name
            year = record.year
            value = record.value
            
            if metric not in data_by_unit[unit]:
                data_by_unit[unit][metric] = {}
            data_by_unit[unit][metric][year] = f"{value:.2f}"
        
        # 转换为表格格式
        for unit, indicators in data_by_unit.items():
            for indicator, years in indicators.items():
                historical_data.append({
                    'unit': unit,
                    'indicator': indicator,
                    'year2021': years.get(2021, '-'),
                    'year2022': years.get(2022, '-'),
                    'year2023': years.get(2023, '-'),
                    'year2024': years.get(2024, '-')
                })
        
        # 获取预测数据总览 - 使用任务的UUID
        actual_task_id = task.task_id  # 使用UUID而不是数字ID
        prediction_results = PredictionResult.query.filter_by(task_id=actual_task_id).all()
        print(f"查询预测结果，使用UUID: {actual_task_id}, 找到{len(prediction_results)}条记录")
        
        # 如果没有找到预测结果，尝试用数字ID查询
        if not prediction_results and task_id.isdigit():
            prediction_results = PredictionResult.query.filter_by(task_id=task_id).all()
            print(f"用数字ID查询预测结果: {task_id}, 找到{len(prediction_results)}条记录")
            
        # 打印前几条记录用于调试
        if prediction_results:
            for i, result in enumerate(prediction_results[:3]):
                print(f"预测结果{i+1}: 板块={result.company_name}, 年份={result.prediction_year}, 收入={result.predicted_sales_amount}")
        else:
            print("没有找到任何预测结果")
        prediction_overview = {
            'years': ['2025', '2026', '2027', '2028', '2029', '2030'],
            'segments': []
        }
        
        # 按业务板块分组预测数据
        segments_data = {}
        for result in prediction_results:
            # 使用 company_name 作为板块名称
            sector_name = result.company_name
            if sector_name not in segments_data:
                segments_data[sector_name] = {}
            
            # 使用 prediction_year 作为年份
            year = result.prediction_year
            
            # 计算净利润（使用 predicted_sales_amount 作为收入，predicted_unit_profit 作为单位利润）
            revenue = result.predicted_sales_amount
            profit = result.predicted_unit_profit if result.predicted_unit_profit else 0
            
            # 如果comprehensive_rate为None，尝试计算简单的年度增长率
            growth_rate = 0.0
            if result.comprehensive_rate is not None:
                growth_rate = result.comprehensive_rate * 100
            else:
                # 对于没有综合增长率的数据，可以使用一个默认值或者基于收入的简单计算
                # 这里我们使用一个基于板块的默认增长率
                sector_default_rates = {
                    '人药制剂板块': 7.8,
                    '人药原料板块': 14.0,
                    '植保板块': 2.86,
                    '动保板块': 7.5,
                    '齐鲁制药集团': 8.0  # 集团默认增长率
                }
                growth_rate = sector_default_rates.get(sector_name, 5.0)  # 默认5%
            
            segments_data[sector_name][year] = {
                'revenue': f"{revenue:.2f}",
                'profit': f"{profit:.2f}",
                'growthRate': f"{growth_rate:.2f}"
            }
        
        for sector, years in segments_data.items():
            segment_data = {
                'name': sector,
                'years': []
            }
            for year in prediction_overview['years']:
                year_data = years.get(int(year), {
                    'revenue': '0.00',
                    'profit': '0.00',
                    'growthRate': '0.00'
                })
                segment_data['years'].append(year_data)
            prediction_overview['segments'].append(segment_data)
        
        # 组合历史数据和预测数据用于图表展示
        chart_data = {
            'years': [2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030],
            'historical_years': [2021, 2022, 2023, 2024],
            'prediction_years': [2025, 2026, 2027, 2028, 2029, 2030],
            'revenue_data': {},  # 收入数据
            'profit_data': {},   # 净利润数据
            'profit_margin_data': {},  # 净利润率数据
            'growth_rate_data': {}     # 综合增长率数据
        }
        
        # 处理历史数据
        for record in historical_records:
            unit = record.business_unit
            if unit not in chart_data['revenue_data']:
                chart_data['revenue_data'][unit] = {}
                chart_data['profit_data'][unit] = {}
                chart_data['profit_margin_data'][unit] = {}
            
            year = record.year
            if record.metric_name == '销售收入':
                chart_data['revenue_data'][unit][year] = record.value
            elif record.metric_name == '净利润':
                chart_data['profit_data'][unit][year] = record.value
            elif record.metric_name == '净利润率':
                chart_data['profit_margin_data'][unit][year] = record.value
        
        # 处理预测数据
        for result in prediction_results:
            sector_name = result.company_name
            year = result.prediction_year
            
            if sector_name not in chart_data['revenue_data']:
                chart_data['revenue_data'][sector_name] = {}
            if sector_name not in chart_data['profit_data']:
                chart_data['profit_data'][sector_name] = {}
            if sector_name not in chart_data['growth_rate_data']:
                chart_data['growth_rate_data'][sector_name] = {}
            
            # 预测收入和利润数据
            chart_data['revenue_data'][sector_name][year] = result.predicted_sales_amount
            chart_data['profit_data'][sector_name][year] = result.predicted_unit_profit if result.predicted_unit_profit else 0
            
            # 综合增长率数据
            if result.comprehensive_rate is not None:
                growth_rate = result.comprehensive_rate * 100
            else:
                sector_default_rates = {
                    '人药制剂板块': 7.8,
                    '人药原料板块': 14.0,
                    '植保板块': 2.86,
                    '动保板块': 7.5,
                    '齐鲁制药集团': 8.0
                }
                growth_rate = sector_default_rates.get(sector_name, 5.0)
            
            chart_data['growth_rate_data'][sector_name][year] = growth_rate
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': {
                'task': {
                    'task_name': task.task_name,
                    'task_id': task.task_id,
                    'created_at': task.created_at.isoformat() if task.created_at else None
                },
                'historicalData': historical_data,
                'metasoOverview': metaso_overview,
                'predictionOverview': prediction_overview,
                'chartData': chart_data,
                'aiAnalysis': {
                    'exists': ai_analysis_exists,
                    'content': ai_analysis_content
                }
            }
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

